/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.rantipin.GUI;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import ru.rantipin.persistence.PersistenceHelper;

/**
 *
 * @author rantipin
 */
public class DataBaseElementDialog extends JDialog{
    
    public enum Type {
        FILM("Formula creation", "Formula components", "Component", "Mass", "%", "Description"),
        CALENDER("Calender creation", "Calender elements", "Element", "Unit", "Description");

        private String title;
        private String tableTitle;
        private String[] strList;

        Type(String title, String tableTitle, String... strList) {
            this.title = title;
            this.tableTitle = tableTitle;
            this.strList = strList;
        }

        public String getTitle() {
            return title;
        } 

        public String getTableTitle() {
            return tableTitle;
        }

        public String[] getParams() {
            return strList;
        }
    }
    
    private static String ICON = "/images/db.png";
    
    public DataBaseElementDialog (Type type, JFrame main) {
        this.type = type;
        
        setTitle(type.getTitle());
        
        ImageIcon icon = new ImageIcon(getClass().getResource(ICON));
        setIconImage(icon.getImage());
        
        setModal(true);
        setSize(400, 500);
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        initComponentsLayout();
        
        setLocationRelativeTo(main);
        setVisible(true);
    }
    
    private void initComponentsLayout() {
        GridBagLayout gridbag = new GridBagLayout();
        setLayout(gridbag);
        
        gridbag.setConstraints(getNameLable(), 
                new GridBagConstraints(
                    0, 0,
                    GridBagConstraints.REMAINDER, 1,
                    0.0, 0.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        add(getNameLable());
        
        gridbag.setConstraints(getTextField(), 
                new GridBagConstraints(
                    0, 1,
                    GridBagConstraints.REMAINDER, 1,
                    0.0, 0.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        add(getTextField());
        
        gridbag.setConstraints(getDescriptionLabel(), 
                new GridBagConstraints(
                    0, 2,
                    GridBagConstraints.REMAINDER, 1,
                    0.0, 0.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        add(getDescriptionLabel());
        
        JScrollPane area = new JScrollPane(getTextArea());
        area.setMinimumSize(new Dimension(0, 60));
        area.setPreferredSize(new Dimension(0, 60));
        gridbag.setConstraints(area, 
                new GridBagConstraints(
                    0, 3,
                    GridBagConstraints.REMAINDER, 1,
                    0.0, 0.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        add(area);
        
        JPanel pane = new JPanel();
        pane.setBorder(BorderFactory.createTitledBorder(type.getTableTitle()));
        pane.setLayout(gridbag);
        
        JScrollPane scrollTable = new JScrollPane(getTable());
        gridbag.setConstraints(scrollTable, 
                new GridBagConstraints(
                    0, 0,
                    GridBagConstraints.REMAINDER, 1,
                    1.0, 1.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.BOTH,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        pane.add(scrollTable);
        
        gridbag.setConstraints(getAddButton(), 
                new GridBagConstraints(
                    0, 1,
                    1, 1,
                    1.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(10, 10, 10, 10),
                    0, 0
                ));
        pane.add(getAddButton());
        
        gridbag.setConstraints(getDeleteButton(), 
                new GridBagConstraints(
                    1, 1,
                    1, 1,
                    0.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(10, 0, 10, 10),
                    0, 0
                ));
        pane.add(getDeleteButton());
        
        gridbag.setConstraints(pane, 
                new GridBagConstraints(
                    0, 4,
                    GridBagConstraints.REMAINDER, 1,
                    1.0, 1.0,
                    GridBagConstraints.LINE_START, GridBagConstraints.BOTH,
                    new Insets(10, 10, 0, 10),
                    0, 0
                ));
        add(pane);
        
        gridbag.setConstraints(getSaveButton(), 
                new GridBagConstraints(
                    0, 5,
                    1, 1,
                    1.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(10, 10, 10, 10),
                    0, 0
                ));
        add(getSaveButton());
        
        gridbag.setConstraints(getCancelButton(), 
                new GridBagConstraints(
                    1, 5,
                    1, 1,
                    0.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(10, 0, 10, 10),
                    0, 0
                ));
        add(getCancelButton());
        
    }
    
    
    private JLabel getNameLable() {
        if (nameLabel == null) {
            nameLabel = new JLabel("Name:");
        }
        
        return nameLabel;
    }

    private JTextField getTextField() {
        if (nameTextField == null) {
            nameTextField = new JTextField();
        }
        
        return nameTextField;
    }

    private JLabel getDescriptionLabel() {
        if (discriptionLabel == null) {
                discriptionLabel = new JLabel("Description:");
        }
        
        return discriptionLabel;
    }

    private JTextArea getTextArea() {
        if (discriptionArea == null) {
                discriptionArea = new JTextArea();
                discriptionArea.setLineWrap(true);
                discriptionArea.setWrapStyleWord(true);
        }
        
        return discriptionArea;
    }

    private JButton getSaveButton() {
        if (saveButton == null) {
            saveButton = new JButton("Save");
            saveButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
//                    try {
//                        TableCellEditor tbce = table.getCellEditor();
//                        if (tbce != null) {
//                            tbce.stopCellEditing();
//                        }
//                        validation();
//                        String[][] tb_data = new String [table.getRowCount()][table.getColumnCount()];
//                        for (int i = 0; i < table.getRowCount(); i++)
//                            for(int j = 0; j < table.getColumnCount(); j++)
//                                tb_data[i][j] = (String)table.getModel().getValueAt(i,j);
//                        if (type == type.CALENDER) {
//                            PersistenceHelper.getInstance().addCalander(nameTextField.getText(),
//                                discriptionArea.getText(), tb_data);
//                        } else {
//                            PersistenceHelper.getInstance().addFormula(nameTextField.getText(),
//                                      discriptionArea.getText(), tb_data);
//                        }
//                        JOptionPane.showMessageDialog(DataBaseElementDialog.this, "Data saved",
//                                      "Data save information", JOptionPane.INFORMATION_MESSAGE);
//                        dispose();
//                    } catch(Exception ex) {
//                        JOptionPane.showMessageDialog(DataBaseElementDialog.this, "Data error: " + ex.getMessage(),
//                                      "Connection test warning", JOptionPane.WARNING_MESSAGE);
//                    }
                }
            });
        }
        
        return saveButton;
    }
    
    private JButton getCancelButton() {
        if (cancelButton == null) {
            cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
        }
        
        return cancelButton;
    }

    private JButton getAddButton() {
        if (addButton == null) {
            addButton = new JButton("Add");
            addButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    tbmodel.addRow(new Object[]{});
                }
            });
            
        }
        
        return addButton;
    }

    private JButton getDeleteButton() {
        if (deleteButton == null) {
            deleteButton = new JButton("Delete");
            deleteButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (table.getSelectedRow()!=-1) {
                        tbmodel.removeRow(table.getSelectedRow());
                    } else if (table.getRowCount()!=0) {
                        tbmodel.removeRow(table.getRowCount()-1);
                    }
                }
            });
        }
        
        return deleteButton;
    }
    
    private JTable getTable() {
        if (table == null) {
            tbmodel = new DefaultTableModel(new Object[0][type.getParams().length], type.getParams());
            table = new JTable(tbmodel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            
        }      
        return table;
    }

    private void validation() throws Exception{
        if (nameTextField.getText().equals("")) {
            throw new Exception("User name should not be empty");
        }
        if (discriptionArea.getText().equals("")) {
            throw new Exception("Description should not be empty");
        }
        for (int i = 0; i < table.getRowCount(); i++) {
            for (int j = 0; j < table.getColumnCount(); j++) {
                String temp = (String)table.getModel().getValueAt(i,j);                        
                if (temp!=null && !temp.equals("")){
                    if (table.getColumnCount() == 4 && (j == 1 || j == 2)) {
                        try {
                            if (Double.parseDouble(temp) < 0){
                                throw new Exception("Namber at cell[ row=" +
                                                     i + ", " + "column=" + j + " ] must be positive");                                
                            }
                        } catch (NumberFormatException nfe){
                            throw new Exception("Incorretc data at cell[ row=" +
                                                 i + ", " + "column=" + j + " ]");
                        }
                    }
                } else {
                    throw new Exception("Some cells in table is empty");
                }
            }
        } 
        
    }
    private Type type = null;
    private JLabel nameLabel = null;
    private JTextField nameTextField = null;
    private JLabel discriptionLabel = null;
    
    private JTextArea discriptionArea = null;
    private JTable table = null;
    private DefaultTableModel tbmodel;
    private JButton addButton = null;
    private JButton deleteButton = null;
    private JButton saveButton = null;
    private JButton cancelButton = null;
}
